import express, { Request, Response, Router } from 'express';
import { PrismaClient } from '@prisma/client';
import { authMiddleware } from '../middleware/auth';
import { ApiResponse } from '../utils/response';
import { priceService } from '../services/priceService';

const router: Router = express.Router();
const prisma = new PrismaClient();

// 获取钱包概览数据
router.get('/overview', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;

    // 获取用户余额
    let userBalance = await prisma.userBalance.findUnique({
      where: { userId }
    });

    if (!userBalance) {
      userBalance = await prisma.userBalance.create({
        data: {
          userId,
          balance: 0,
          frozen: 0,
          total: 0
        }
      });
    }

    // 获取质押信息
    const stakingInfo = await prisma.userStaking.findFirst({
      where: { userId }
    });

    // 获取NEAR实时价格
    const nearPrice = await priceService.getNearPrice();

    // C: 质押本金NEAR（存入的NEAR数量）
    const nearStaked = Number(stakingInfo?.stakedAmount || 0);

    // 使用历史结算记录汇总收益
    const stakingSettlementSum = await prisma.stakingSettlement.aggregate({
      where: { userId },
      _sum: {
        rewardKrw: true,
        rewardNear: true
      }
    });
    const aggregatedRewardsNear = Number(stakingSettlementSum._sum.rewardNear || 0);

    const storedTotalRewardsNear = Number(stakingInfo?.totalRewardsNear || 0);
    const totalRewardsNear = storedTotalRewardsNear > 0 ? storedTotalRewardsNear : aggregatedRewardsNear;
    const totalRewardsValue = totalRewardsNear * nearPrice;

    const freeBalanceKrw = Number(userBalance.balance || 0);
    const frozenBalanceKrw = Number(userBalance.frozen || 0);
    const totalValue = freeBalanceKrw + (nearStaked * nearPrice);
    const freeHoldingNear = nearPrice > 0
      ? Number((freeBalanceKrw / nearPrice).toFixed(6))
      : 0;
    const totalNearHolding = freeHoldingNear + nearStaked;

    const todayDistributedNear = Number(stakingInfo?.dailyRewardDistributed || 0);
    const dayChange = todayDistributedNear * nearPrice;
    const dayChangeRate = totalValue > 0
      ? Number((dayChange / totalValue).toFixed(4))
      : 0;

    const overview = {
      totalValue, // A: 总资产 = 자유 보유 + 스테이킹 잠금 가치
      availableBalance: totalValue, // 장부 기준总额
      immediateBalance: freeBalanceKrw, // 즉시 사용 가능 KRW
      frozenBalance: frozenBalanceKrw, // 冻结中的KRW
      lockedBalance: nearStaked * nearPrice, // C: 质押本金(KRW)
      totalRewardsValue, // D: 누적质押收益(KRW)，只增不减

      currency: 'KRW',
      dayChange,
      dayChangeRate,

      nearPrice,
      nearBalance: totalNearHolding, // 총 보유 NEAR
      nearStaked, // C: 质押本金 NEAR
      totalRewardsNear, // D: 누적质押收益NEAR数量
      freeHoldingNear, // F: 자유 보유 NEAR
      nearTotalValue: totalValue
    };

    res.json(ApiResponse.success(overview, '지갑 개요 조회에 성공했습니다.'));
  } catch (error) {
    console.error('지갑 개요 조회 오류:', error);
    // 即使发生错误，也返回基础数据确保前端可用
    const fallbackData = {
      totalValue: 0,
      availableBalance: 0,
      lockedBalance: 0,
      totalRewardsValue: 0,
      currency: 'KRW',
      dayChange: 0,
      dayChangeRate: 0,
      nearPrice: 6500,
      nearBalance: 0,
      nearStaked: 0,
      totalRewardsNear: 0,
      freeHoldingNear: 0,
      nearTotalValue: 0
    };
    res.json(ApiResponse.success(fallbackData, '지갑 개요 조회에 성공했습니다(기본 데이터를 사용했습니다).'));
  }
});

// 获取投资统计
router.get('/investment', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;

    // 获取用户的投资记录（客户实际存入的韩元金额）
    let deposits: any[] = [];
    let totalDeposited = 0; // B栏：总投资额（客户存入的韩元）
    try {
      deposits = await prisma.depositRecord.findMany({
        where: {
          userId,
          status: 'CONFIRMED'
        }
      });
      // 计算客户实际存入的韩元总额
      totalDeposited = deposits.reduce((sum, deposit) => sum + Number(deposit.amount), 0);
    } catch (dbError) {
      console.warn('투자 기록 조회에 실패했습니다. 빈 배열을 사용합니다.:', dbError);
    }

    // 获取质押信息
    let stakingInfo = null;
    try {
      stakingInfo = await prisma.userStaking.findFirst({
        where: { userId }
      });
    } catch (stakingError) {
      console.warn('스테이킹 정보 조회에 실패했습니다.:', stakingError);
    }

    const nearPrice = await priceService.getNearPrice();

    // 使用结算记录聚合质押收益（按结算时KRW金额记录，避免汇率波动）
    const stakingSettlementSum = await prisma.stakingSettlement.aggregate({
      where: { userId },
      _sum: {
        rewardKrw: true
      }
    });
    const totalRewardsKrw = Number(stakingSettlementSum._sum.rewardKrw || 0);

    // 总投资额 = 客户存入的韩元
    // 注意：质押本金是管理员存入的NEAR，不计入客户的投资额
    const totalInvestment = totalDeposited;

    // 质押本金价值（用于当前价值计算，但不计入投资额）
    const stakedNear = Number(stakingInfo?.stakedAmount || 0);
    const stakingValue = nearPrice > 0 ? stakedNear * nearPrice : 0;

    // 质押收益KRW（按结算时记录的金额累计）
    const stakingRewardsValue = totalRewardsKrw;

    // 当前价值 = 质押本金 + 质押收益
    const currentValue = stakingValue + stakingRewardsValue;

    const totalReturn = currentValue - totalInvestment;
    const returnRate = totalInvestment > 0 ? (totalReturn / totalInvestment) * 100 : 0;

    // 日变化数据（暂时设为0，等待投资系统实现）
    const dayChange = 0;
    const dayChangeRate = 0;

    const investmentStats = {
      totalInvestment,
      currentValue,
      totalReturn,
      returnRate,
      dayChange,
      dayChangeRate
    };

    res.json(ApiResponse.success(investmentStats, '투자 통계 조회에 성공했습니다.'));
  } catch (error) {
    console.error('투자 통계 조회 오류:', error);
    // 返回默认的投资统计数据
    const fallbackStats = {
      totalInvestment: 0,
      currentValue: 0,
      totalReturn: 0,
      returnRate: 0,
      dayChange: 0,
      dayChangeRate: 0
    };
    res.json(ApiResponse.success(fallbackStats, '투자 통계 조회에 성공했습니다(기본 데이터를 사용했습니다).'));
  }
});

// 获取NEAR资产信息
router.get('/assets', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;

    let userBalance = null;
    let stakingInfo = null;

    // 分别获取数据，每个都有独立的错误处理
    try {
      userBalance = await prisma.userBalance.findUnique({
        where: { userId }
      });
    } catch (balanceError) {
      console.warn('사용자 잔액 조회에 실패했습니다.:', balanceError);
    }

    try {
      stakingInfo = await prisma.userStaking.findFirst({
        where: { userId }
      });
    } catch (stakingError) {
      console.warn('스테이킹 정보 조회에 실패했습니다.:', stakingError);
    }

    const priceData = await priceService.getNearPriceData();
    const nearPrice = priceData.price;
    const nearBalance = userBalance ? Number(userBalance.balance) / nearPrice : 0;
    const nearStaked = Number(stakingInfo?.stakedAmount || 0);
    const totalValue = (nearBalance + nearStaked) * nearPrice;

    // 24小时价格变化
    const change24h = priceData.change24h;
    const changeRate24h = priceData.changeRate24h;

    const nearAsset = {
      symbol: 'NEAR',
      balance: nearBalance,
      lockedAmount: nearStaked,
      priceKRW: nearPrice,
      totalValue,
      change24h,
      changeRate24h
    };

    res.json(ApiResponse.success(nearAsset, 'NEAR 자산 정보 조회에 성공했습니다.'));
  } catch (error) {
    console.error('NEAR 자산 정보 조회 오류:', error);
    // 返回默认的资产信息
    const fallbackAsset = {
      symbol: 'NEAR',
      balance: 0,
      lockedAmount: 0,
      priceKRW: 6500,
      totalValue: 0,
      change24h: 0,
      changeRate24h: 0
    };
    res.json(ApiResponse.success(fallbackAsset, 'NEAR 자산 정보 조회에 성공했습니다(기본 데이터를 사용했습니다).'));
  }
});

// 获取投资组合分布
router.get('/portfolio', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;

    let userBalance = null;
    let stakingInfo = null;

    // 分别获取数据，添加错误处理
    try {
      userBalance = await prisma.userBalance.findUnique({
        where: { userId }
      });
    } catch (balanceError) {
      console.warn('사용자 잔액 조회에 실패했습니다.:', balanceError);
    }

    try {
      stakingInfo = await prisma.userStaking.findFirst({
        where: { userId }
      });
    } catch (stakingError) {
      console.warn('스테이킹 정보 조회에 실패했습니다.:', stakingError);
    }

    const nearPrice = await priceService.getNearPrice();
    const availableValue = Number(userBalance?.balance || 0);
    const stakedValue = Number(stakingInfo?.stakedAmount || 0) * nearPrice;
    const totalValue = availableValue + stakedValue;

    let portfolio = [];

    if (totalValue > 0) {
      if (availableValue > 0) {
        portfolio.push({
          asset: 'NEAR (가용)',
          value: availableValue,
          percentage: (availableValue / totalValue) * 100,
          color: '#4f46e5'
        });
      }

      if (stakedValue > 0) {
        portfolio.push({
          asset: 'NEAR (스테이킹)',
          value: stakedValue,
          percentage: (stakedValue / totalValue) * 100,
          color: '#7c3aed'
        });
      }
    } else {
      // 默认空상태
      portfolio = [
        {
          asset: 'NEAR',
          value: 0,
          percentage: 100,
          color: '#9ca3af'
        }
      ];
    }

    res.json(ApiResponse.success(portfolio, '투자 포트폴리오 분포 조회에 성공했습니다.'));
  } catch (error) {
    console.error('투자 포트폴리오 분포 조회 오류:', error);
    // 返回默认的投资组合数据
    const fallbackPortfolio = [
      {
        asset: 'NEAR',
        value: 0,
        percentage: 100,
        color: '#9ca3af'
      }
    ];
    res.json(ApiResponse.success(fallbackPortfolio, '투자 포트폴리오 분포 조회에 성공했습니다(기본 데이터를 사용했습니다).'));
  }
});

export default router;
